package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.TrainingMapper;
import com.ruoyi.system.domain.Training;
import com.ruoyi.system.service.ITrainingService;

/**
 * 培训管理Service业务层处理
 * 
 * @author 汪治敏
 * @date 2025-08-15
 */
@Service
public class TrainingServiceImpl implements ITrainingService 
{
    private static final Logger log = LoggerFactory.getLogger(TrainingServiceImpl.class);

    @Autowired
    private TrainingMapper trainingMapper;

    /**
     * 查询培训管理
     * 
     * @param id 培训管理主键
     * @return 培训管理
     */
    @Override
    public Training selectTrainingById(Long id)
    {
        return trainingMapper.selectTrainingById(id);
    }

    @Override
    public List<Training> selectTrainingListByIds(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return new ArrayList<>();
        }
        return trainingMapper.selectTrainingListByIds(ids);
    }
    /**
     * 查询培训管理列表
     * 
     * @param training 培训管理
     * @return 培训管理
     */
    @Override
    public List<Training> selectTrainingList(Training training)
    {
        return trainingMapper.selectTrainingList(training);
    }

    /**
     * 新增培训管理
     * 
     * @param training 培训管理
     * @return 结果
     */
    @Override
    public int insertTraining(Training training)
    {
        return trainingMapper.insertTraining(training);
    }

    /**
     * 修改培训管理
     * 
     * @param training 培训管理
     * @return 结果
     */
    @Override
    public int updateTraining(Training training)
    {
        return trainingMapper.updateTraining(training);
    }

    /**
     * 批量删除培训管理
     * 
     * @param ids 需要删除的培训管理主键
     * @return 结果
     */
    @Override
    public int deleteTrainingByIds(Long[] ids)
    {
        return trainingMapper.deleteTrainingByIds(ids);
    }

    /**
     * 删除培训管理信息
     * 
     * @param id 培训管理主键
     * @return 结果
     */
    @Override
    public int deleteTrainingById(Long id)
    {
        return trainingMapper.deleteTrainingById(id);
    }

    @Override
    public String importTraining(List<Training> trainingList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(trainingList) || trainingList.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (Training training : trainingList) {
            try {
                // 验证数据
                if (!validateTraining(training)) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、培训名称 " + training.getTrainingName() + " 数据格式不正确");
                    continue;
                }

                // 检查是否存在相同名称的培训
                Training existingTraining = trainingMapper.selectByTrainingName(training.getTrainingName());
                if (existingTraining == null) {
                    // 插入新数据
                    training.setCreateBy(operName);
                    trainingMapper.insertTraining(training);
                    successNum++;
                } else if (updateSupport) {
                    // 更新已有数据
                    training.setId(existingTraining.getId());
                    training.setUpdateBy(operName);
                    trainingMapper.updateTraining(training);
                    successNum++;
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、培训名称 " + training.getTrainingName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、培训名称 " + training.getTrainingName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }

        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 验证培训数据格式
     */
    private boolean validateTraining(Training training) {
        // 验证必填字段
        if (StringUtils.isEmpty(training.getTrainingName()) ||
                StringUtils.isEmpty(training.getManager()) ||
                StringUtils.isEmpty(training.getEmail()) ||
                StringUtils.isEmpty(training.getPhone()) ||
                training.getStartDate() == null ||
                training.getEndDate() == null) {
            return false;
        }

        // 验证邮箱格式
        if (!isEmail(training.getEmail())) {
            return false;
        }

        // 验证手机号格式
        if (!isMobile(training.getPhone())) {
            return false;
        }

        // 验证培训时间不超过6天
        long diffInMillies = Math.abs(training.getEndDate().getTime() - training.getStartDate().getTime());
        long diffInDays = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
        if (diffInDays > 6) {
            return false;
        }

        // 验证结束时间不早于开始时间
        if (training.getEndDate().before(training.getStartDate())) {
            return false;
        }

        return true;
    }

    /**
     * 验证邮箱格式
     */
    private boolean isEmail(String email) {
        if (StringUtils.isEmpty(email)) {
            return false;
        }
        String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
        Pattern pattern = Pattern.compile(emailRegex);
        return pattern.matcher(email).matches();
    }

    /**
     * 验证手机号格式
     */
    private boolean isMobile(String mobile) {
        if (StringUtils.isEmpty(mobile)) {
            return false;
        }
        String mobileRegex = "^1[3-9]\\d{9}$";
        Pattern pattern = Pattern.compile(mobileRegex);
        return pattern.matcher(mobile).matches();
    }

    @Override
    public List<Training> getTrainingListByYearAndMonth(String year, String month){
        return trainingMapper.selectTrainingListByYearAndMonth(year, month);
    }
}
